using System;
using System.Collections.Generic;
using System.Web;
using DecisionMaking.BusinessLogic;
using DecisionMaking.BusinessLogic.Model;
using MvcContrib;
using System.Web.Mvc;

namespace DecisionMaking.WebApp.Controllers
{
    [HandleError]
    [Authorize]
    public class SimulationController : BaseController
    {
        /// <summary>
        /// Injected by Windsor 
        /// </summary>
        public IAlgorithmManager AlgorithmManager { private get; set; }
        public IExecutionManager ExecutionManager { private get; set; }
        
        [HttpGet]
        public ActionResult Run(int id)
        {
            var model = new RunSimulationModel
            {
                EnvironmentId = id,
                AlgorithmDefinitions = AlgorithmManager.GetAlgorithmDefinitions(CurrentAccount.Id)
            };

            return View("Run", model);
        }

        [HttpPost]
        public ActionResult Run(RunSimulationModel model)
        {
            if (ModelState.IsValid)
            {
                var simulationId = ExecutionManager.ExecuteEnvironment(model.DefinitionId, model.EnvironmentId);
                return Json(new {simulationId});
            }

            return View("Run", model);
        }

        [HttpGet]
        public ActionResult PollProgress(Guid simulationId)
        {
            var e = ExecutionManager.GetLastException(simulationId);

            var result = new
            {
                done = ExecutionManager.GetExecutionProgress(simulationId),
                errorMessage = e == null ? null : e.Message
            };

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}